#!/usr/bin/python
#    pyPastebot 0.32 beta by goldenwolf djaswal@ryerson.ca
#    Special thanks to warg for all his contribution
#    pyPastebot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    pyPastebot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import socket
import sys
import time
import os
import time
import modulefile
from irclib import nm_to_n, irc_lower, all_events
from ircbot import SingleServerIRCBot
from base64 import urlsafe_b64encode, urlsafe_b64decode

#Pastebin bot config
HOST = "nullwolfie.org"     # IRC server's address
PORT = 6667				    # IRC server's port
NICK = "Pypy"               # Nickname of bot
CHAN = "#opers"             # Channel to join
FINISH = "==="             # Command which tells the bot when the PASTE is done
ADMIN = "GW"                # Name of admin to contact during trouble
MAXLINES = 150              # Maximum lines bot will paste, anything more will cause bot to go defensive

# Pastebin web config
NAME = "PyPaster"           # Name that will appear after the pastes are completed
EMAIL = "pypaster@null"     # Email that will appear on the pastebin
SUBD = "pypaster"           # Subdomain to pastes at, i.e "pymaster.pastebin.com"
TIME = "1D"                 # How long paste will exist on pastebin,  "10M" = 10 Minutes, "1H" = 1 Hour, "1D" = 1 day, "1M" = 1 Month, "N" = Never
FORMAT = "python"           # Enable Syntax Highlighting, Full list can be found in Syntax.txt

class pypaster(SingleServerIRCBot):

    def __init__(self, NICK, HOST, PORT, CHAN):
        SingleServerIRCBot.__init__(self, [(HOST, PORT)], NICK, NICK)
        self.channel = CHAN
        self.nickname = NICK
        self.start()

    def on_welcome(self, c, e):
        c.join(self.channel)

    def on_ctcp(self, c, e):
        if e.arguments()[0] == "VERSION":
            c.ctcp_reply(nm_to_n(e.source()), "VERSION pypastebot by goldenwolf djaswal@ryerson.ca")

    def on_privmsg(self, c, e):
        nick_name = nm_to_n(e.source())
        finame = urlsafe_b64encode(nick_name)
        fname = open(finame, 'a+')
        if (self.before_write(c, e)) > MAXLINES:
            fname.close()
            os.remove(nick_name)
            c.privmsg(ADMIN, "Possible flood detected from %s" % nick_name)
            c.privmsg(nick_name, "Max lines of %s exceeded. Paste not posted. Use website http://www.pastebin.com for long pastes" % MAXLINES)
        self.write_file(c, e, fname)

    def before_write(self, c, e):
        num_lines = sum(1 for line in open(urlsafe_b64encode(nm_to_n(e.source()))))
        return num_lines

    def write_file(self, c, e, fname):
        if (e.arguments()[0]) != FINISH:
            try:
                fname.write(e.arguments()[0] + '\n')
                fname.flush()
            except Exception, err:
                c.privmsg(ADMIN, "Error encountered while parsing messages and writing to file.")
        else:
            self.submit_file(c, e, fname)

    def submit_file(self, c, e, fname):
        nick_name = nm_to_n(e.source())
        if(os.path.isfile(urlsafe_b64encode(nick_name))):
            try:
                pastey = fname.read()
                name = modulefile.Pastebin(pastey, NAME, EMAIL, SUBD, TIME, FORMAT)
                result = name.submit()
                c.privmsg(nick_name, "Done: %s" % result)
                fname.close()
                os.remove(urlsafe_b64encode(nick_name))
            except Exception, err:
                c.privmsg(ADMIN, "Error encountered while pasting to pastebin Perhaps I/O error.")

def main ():
    server = pypaster(NICK, HOST, PORT, CHAN)

if __name__ == "__main__":
    main()